package com.example.juejincheck.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.tea.utils.StringUtils;
import com.example.juejincheck.config.RedisCache;
import com.example.juejincheck.dao.FeidianConfigDao;
import com.example.juejincheck.dao.JueJinAssignAccountDao;
import com.example.juejincheck.dao.MotianlunAccountDao;
import com.example.juejincheck.domain.FeidianConfig;
import com.example.juejincheck.domain.JuejinAssignAccount;
import com.example.juejincheck.domain.MotianlunAccount;
import com.example.juejincheck.utils.FileUtils;
import com.example.juejincheck.utils.HttpUtil;
import com.example.juejincheck.utils.TianxingUtils;
import com.example.juejincheck.utils.ToHtmlUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author yangkun
 * @description
 * @date 2023年01月17日 8:42
 */
@Slf4j
@Component
public class JobService {

    @Value("${file.dirpath}")
    private String fileDirPath;
    @Autowired
    private RedisCache redisCache;
    // 登录
    private static final String LOGIN_URL = "https://www.modb.pro/api/login";
    // 签到
    private static final String ASSIGN_URL = "https://www.modb.pro/api/user/checkIn";
    // 抽奖
    private static final String LOTTERY_NUM_URL = "https://www.modb.pro/api/points/lotteryNum";
    // 抽奖
    private static final String LOTTERY_URL = "https://www.modb.pro/api/points/lottery";
    // 发布数说
    private static final String DATALKS_URL = "https://www.modb.pro/api/datalks/save";
    // 今日新增
    private static final String USER_DAILY_TASK_URL = "https://www.modb.pro/api/user/dailyTask";
    // 当前墨值
    private static final String USER_DETAIL_URL = "https://www.modb.pro/api/user/detail";
    // 发布文章
    private static final String KNOWLEDGES_SAVE_URL = "https://www.modb.pro/api/knowledges/save";
    // 上传文档
    private static final String UPLOAD_FILE_URL = "https://www.modb.pro/api/dbdocs";
    // 文档列表
    private static final String FILE_LIST_URL = "https://www.modb.pro/api/dbdocs/consoleList?pageNum=1&pageSize=10";
    // 墨值详情
    private static final String MOZHI_URL = "https://www.modb.pro/api/points/pointHistories?pageNum=1&pageSize=10&userId=";
    // 发布沸点
    private static final String PUBLISH_SHORT_MSG_URL = "https://api.juejin.cn/content_api/v1/short_msg/publish";
    // 沸点列表
    private static final String SHORT_MSG_URL = "https://api.juejin.cn/content_api/v1/short_msg/query_list";
    // 文章列表
    private static final String ARTICLE_LIST_URL = "https://api.juejin.cn/recommend_api/v1/article/recommend_all_feed";
    // 文章详情
    private static final String ARTICLE_DETAIL_URL = "https://juejin.cn/post/";
    // 时间格式化
    private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    @Resource
    private MiniprogramService miniprogramService;


    public void noticeShortMsg(JuejinAssignAccount juejinAssignAccountPO, FeidianConfig feidianConfig) {
        // 查询当日沸点
        JSONObject map = new JSONObject();
        map.put("cursor", "0");
        map.put("limit", 20);
        map.put("sort_type", 4);
        map.put("user_id", juejinAssignAccountPO.getUserId());
        String shortMsgList = HttpUtil.sendPost(SHORT_MSG_URL, juejinAssignAccountPO.getCookie(), map);
        JSONArray data = JSONObject.parseObject(shortMsgList).getJSONArray("data");
        Date today = new Date();
        boolean isPublish = false;
        for (int i = 0; i < data.size(); i++) {
            JSONObject jsonObject = data.getJSONObject(i).getJSONObject("msg_Info");
            String ctime = jsonObject.getString("ctime");
            String theme_id = jsonObject.getString("theme_id");
            Date date = new Date(Long.valueOf(ctime)*1000);
            if(DateUtil.isSameDay(today, date) && feidianConfig.getThemeId().equals(theme_id)){
                isPublish = true;
            }
        }
        if(!isPublish){
            log.info("活动" + feidianConfig.getThemeTitle() + "下，今天你还没发布该话题下的沸点参加活动哦！不要忘记了");
            miniprogramService.sendMsg(juejinAssignAccountPO, feidianConfig);
        }
    }

    public static JSONArray getArticles(String juejinCookie) {
        JSONObject map = new JSONObject();
        map.put("cursor", "0");
        map.put("limit", 20);
        map.put("id_type", 2);
        map.put("sort_type", 200);
        map.put("client_type", 2608);
        String shortMsgList = HttpUtil.sendPost(ARTICLE_LIST_URL, juejinCookie, map);
        return JSONObject.parseObject(shortMsgList).getJSONArray("data");
    }

    public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
        if (nowTime.getTime() == startTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        return date.after(begin) && date.before(end);
    }
    /**
     *
     * @description 掘金自动发沸点
     * @author yangkun
     * @date 2022/12/6 8:54
     * @param cookie
     * @return java.util.List<java.lang.String>
     */
    public void publishShortMsg(String cookie) {
        try {
            log.info("开始随机发沸点");
            JSONObject map = new JSONObject();
            map.put("content", TianxingUtils.getGoodMorning());
            map.put("sync_to_org", false);
            String assignResult = HttpUtil.sendPost(PUBLISH_SHORT_MSG_URL, cookie, map);
            log.info("随机发沸点结果: {}", assignResult);
        } catch (Exception e) {
            log.error("随机发沸点失败", e);
        }
    }
    /**
     * 墨天伦签到签到
     *
     */
    public boolean assign(MotianlunAccount motianlunAccount) {
        try {
            String cookie = HttpUtil.doLogin(LOGIN_URL, motianlunAccount.getPhoneNum(), motianlunAccount.getPassword());
            Map<String, String> header = new HashMap<>();
            header.put("Cookie", cookie);
            String assignResult = HttpUtil.sendPost(ASSIGN_URL, cookie, new JSONObject());
            JSONObject jsonObject = JSONObject.parseObject(assignResult);
            Boolean success = jsonObject.getBoolean("success");
            JSONObject param = new JSONObject();
            param.put("content", TianxingUtils.getGoodMorning());
            param.put("imageUrls", new JSONArray());
            param.put("polls", null);
            param.put("topicId", "");
            param.put("videoUrl", "");
            String saveResult = HttpUtil.sendPost(DATALKS_URL, cookie, param);
            JSONObject saveJson = JSONObject.parseObject(saveResult);
            JSONArray articles = getArticles(motianlunAccount.getJuejinCookie());
            JSONObject saveArticleJSON;
//            for (int i = 0; i < 20; i++) {
//                saveArticleJSON = publishArticle(cookie, header, articles.getJSONObject(i));
////                log.info("发布文章结果：{}", saveArticleJSON);
//                if(saveArticleJSON.getBoolean("success")){
//                   break;
//                }
//            }
            String lottery = HttpUtil.doGet(LOTTERY_NUM_URL, new HashMap<>(), header);
            JSONObject jsonObject1 = JSONObject.parseObject(lottery);
            String notice = "";
            if(jsonObject1.getInteger("lotteryNum") != null && jsonObject1.getInteger("lotteryNum") != 0){
                String lotteryResult = HttpUtil.sendPost(LOTTERY_URL, cookie, new JSONObject());
                JSONObject lotteryJSON = JSONObject.parseObject(lotteryResult);
                if(lotteryJSON.getBoolean("success")){
                    String message = lotteryJSON.getString("operateMessage");
                    JSONObject operateCallBackObj = lotteryJSON.getJSONObject("operateCallBackObj");
                    String name = operateCallBackObj.getString("name");
                    notice = "免费抽奖："+message+"，获得奖品："+name+"，";
                    // 发送消息通知
                }
            }
//            uploadFile(cookie, motianlunAccount.getPhoneNum());
            String userDetail = HttpUtil.doGet(USER_DETAIL_URL, new HashMap<>(), header);
            JSONObject userDetailJSON = JSONObject.parseObject(userDetail);
            String userDailyTask = HttpUtil.doGet(USER_DAILY_TASK_URL, new HashMap<>(), header);
            JSONObject userDailyTaskJSON = JSONObject.parseObject(userDailyTask);
            // 上传文档
            notice+="今日新增墨值："+userDailyTaskJSON.getInteger("todayPoints")+"，当前总墨值："+userDetailJSON.getInteger("point")+"，今日墨值明细：<br/>";
            String mozhiDetail = HttpUtil.doGet(MOZHI_URL, new HashMap<>(), header);
            JSONArray list1 = JSONObject.parseObject(mozhiDetail).getJSONArray("list");
            Date today = new Date();
            for (int i = 0; i < list1.size(); i++) {
                JSONObject jsonObject2 = list1.getJSONObject(i);
                String createdTime = jsonObject2.getString("createdTime");
                if (DateUtil.isSameDay(today, DateUtil.parse(createdTime, "yyyy-MM-dd HH:mm:ss"))) {
                    notice+=(i+1)+"、获取操作："+jsonObject2.getString("action") +"，墨值+"+jsonObject2.getInteger("delta")+"，详情："+jsonObject2.getString("detail")+"<br>";
                }
            }
            log.info("用户【{}】通知：{}", userDetailJSON.getString("account") ,notice);
            miniprogramService.sendCheckInMsg(motianlunAccount.getPushPlusToken(), notice);
            return success;
//            return true;
        } catch (Exception e) {
            log.error("墨天伦签到失败", e);
        }
        return false;
    }

    private void uploadFile(String cookie, String phoneNum){
        HashMap<String, String> param = new HashMap<>();
        param.put("tags", "java");
        param.put("processStatus", "0");
        param.put("point", "0");
        param.put("encryptLevel", "PUBLIC");
        param.put("positions", "");
        param.put("brief", "");
        param.put("isRepeat", "");
//        File file = new File("C:\\Users\\Administrator\\Desktop\\原文件可参考");
        File file = new File(fileDirPath+"/"+phoneNum);
        if(file.isDirectory()){
            File[] files = file.listFiles();
            if(files.length != 0){
                Integer i = redisCache.getCacheObject(phoneNum);
                if(i == null){
                    i = 0;
                    redisCache.setCacheObject(phoneNum, i);
                }
                log.info(phoneNum+"文件夹的第"+i+"个文件");
                File file1 = files[i];
                param.put("title", file1.getName());
                HashMap<String, String> header= new HashMap<>();
                header.put("Cookie", cookie);
                String assignResult = HttpUtil.doPostUploadFile(UPLOAD_FILE_URL, header, file1, param);
                i++;
                redisCache.setCacheObject(phoneNum, i);
                JSONObject jsonObject = JSONObject.parseObject(assignResult);
                if(jsonObject.getBoolean("success")){
                    try {
                        int processStatus = 0;
                        for (int i1 = 0; i1 < 10; i1++) {
                            Thread.sleep(2000);
                            String s = HttpUtil.doGet(FILE_LIST_URL, new HashMap<>(), header);
                            JSONObject jsonObject1 = JSONObject.parseObject(s);
                            JSONArray list = jsonObject1.getJSONArray("list");
                            JSONObject jsonObject2 = list.getJSONObject(0);
                            if(jsonObject2.getInteger("processStatus") != 0){
                                processStatus = jsonObject2.getInteger("processStatus");
                                break;
                            }
                        }
                        if(processStatus == 2){
                            for (int i1 = 0; i1 < files.length; i1++) {
                                int processStatus1 = 1;
                                Integer i3 = redisCache.getCacheObject(phoneNum);
                                file1 = files[i3];
                                log.info(phoneNum+"文件夹的第"+i3+"个文件");
                                i3++;
                                redisCache.setCacheObject(phoneNum, i3);
                                param.put("title", file1.getName());
                                log.info(param.toString());
                                String assignResult1 = HttpUtil.doPostUploadFile(UPLOAD_FILE_URL, header, file1, param);
                                JSONObject jsonObject1 = JSONObject.parseObject(assignResult1);
                                if(jsonObject.getBoolean("success")){
                                    for (int i2 = 0; i2 < 10; i2++) {
                                        Thread.sleep(2000);
                                        String s = HttpUtil.doGet(FILE_LIST_URL, new HashMap<>(), header);
                                        JSONObject jsonObject2 = JSONObject.parseObject(s);
                                        JSONArray list = jsonObject2.getJSONArray("list");
                                        JSONObject jsonObject3 = list.getJSONObject(0);
                                        if(jsonObject3.getInteger("processStatus") != 0){
                                            processStatus1 = jsonObject3.getInteger("processStatus");
                                            break;
                                        }
                                    }
                                }
                                if(processStatus1 == 1){
                                    break;
                                }
                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.info(assignResult);
            }
        }
    }
    private JSONObject publishArticle(String cookie, Map<String, String> header, JSONObject articleJSON) {
        JSONObject param1 = new JSONObject();
        JSONObject json = new JSONObject();
        String userDetail1 = HttpUtil.doGet(USER_DETAIL_URL, new HashMap<>(), header);
        String articleId = "";
        String title = "";
        String content = "";
        if(articleJSON.getJSONObject("item_info").getJSONObject("article_info") != null){
            articleId = articleJSON.getJSONObject("item_info").getString("article_id");
            title = articleJSON.getJSONObject("item_info").getJSONObject("article_info").getString("title");
        }else{
            json.put("success", false);
            return json;
        }
        if(title.length() <= 15){
            json.put("success", false);
            return json;
        }
        HttpURLConnection connection = null;
        try {
            URL getUrl = new URL(ARTICLE_DETAIL_URL + articleId);
            connection = (HttpURLConnection) getUrl.openConnection();
            connection.connect();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            StringBuffer sb = new StringBuffer();
            while ((lines = reader.readLine()) != null) {
                // System.out.println(lines);
                sb.append(lines + "\n");
            }
            reader.close();
            Document document = Jsoup.parse(sb.toString());
            Elements divTags = document.getElementsByClass("article-content");
            int size = divTags.size();
            if(size != 0){
                Element element = divTags.get(0);
                content = element.html();
            }else {
                content = "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                connection.disconnect();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        JSONObject userDetailJSON1 = JSONObject.parseObject(userDetail1);
        System.out.println(content);
        param1.put("answer", content);
        param1.put("answerMd", "");
        param1.put("askMd", "");
        param1.put("brief", "");
        param1.put("encryptLevel", "PUBLIC");
        param1.put("imageUrl", "");
        param1.put("source", userDetailJSON1.getString("account"));
        param1.put("sourceId", "");
        param1.put("title", title);
        param1.put("status", 0);
        param1.put("type", 1);
        param1.put("tags", new ArrayList<>());
        param1.put("url", null);
        String knowl = HttpUtil.sendPost(KNOWLEDGES_SAVE_URL, cookie, param1);
        JSONObject knowJSON = JSONObject.parseObject(knowl);
        Integer id = knowJSON.getJSONObject("operateCallBackObj").getInteger("id");
        param1.put("id", id);
        List<String> list = new ArrayList<>();
        list.add("墨力计划");
        param1.put("tags", list);
        param1.put("status", 1);
        log.info(param1.toString());
        String saveArticle = HttpUtil.sendPost(KNOWLEDGES_SAVE_URL, cookie, param1);
        JSONObject saveArticleJSON = JSONObject.parseObject(saveArticle);
        return saveArticleJSON;
    }

    public static void sun(Integer i){
        int count = 0;
        Integer g = i;
        while (g>=1){
            g/=10;
            count++;
        }
        if(count > 1){
            int t = 1;
            for (int i1 = 0; i1 < (count-1); i1++) {
                t*=10;
            }
            int b = i / t;
            System.out.println(b);
            int yu = i % t;
            sun(yu);
        }else if(count == 1){
            System.out.println(i);
        }
    }

    /**
     *
     * @description 发送早安语录
     * @author yangkun
     * @date 2023/1/17 8:45
     */
    public void sendWechatToUser() {
        miniprogramService.sendWechatToUser();
    }
}
